<?php
class shopcarController extends Controller {

    function __construct() {
        parent::__construct();
    }

    function adminList() {
        $this->debugmsg('shopcarController::adminList');

        $this->needAdmin();

        $data['admin']      = true;
        $data['pagesize']   = 20;

        $data['sort']       = trim($this->request['sort']);
        $data['sortorder']  = 'desc';

        $result['list'] = $this->model->shopCarList($data);

        return $result;
    }

    function shopCarList() {
        $this->debugmsg('shopcarController::shopCarList');

        $data['sessionid']  = $this->session['sid'];
        $data['sort']       = 'id';

        //更新购物车
        //if ($this->get || $this->request)
        $r = $this->shopCarUpdate();

        do_action('shopcar_shopCarList_Befor', $this->session['sid']);

        $result = $this->model->shopCarList($data);
        $result['ajaxcode'] = ($r ? $r['ajaxcode'] : 1);

        $this->session['caramount'] = $result['totalamount'];
        $this->session['carprice'] = $result['totalprice'];

        do_action('shopcar_shopCarList', array('result'=>&$result));

        return $result;
    }

    function shopCarUpdate() {
        $this->debugmsg('shopcarController::shopCarUpdate');

        $data['sessionid'] = $this->session['sid'];

        //清空
        if ($data['emptycar'] = intval($this->request['emptycar'])) {
            $result['ajaxcode'] = $this->model->shopCarUpdate($data) ? 1 : 2;

            //删除过来的wishlist
            if ($this->session['wish']) unset($this->session['wish']);
        } else {
            $result['ajaxcode'] = 1;
            foreach ($this->request as $k=>$v) {
                if (!preg_match('/^amount/i', $k)) continue;

                $data['id']     = intval(str_replace('amount', '', $k));
                $data['amount'] = abs(intval($v));

                $tmp = $this->model->shopCarUpdate($data);
                if ($tmp['code']['shopCarUpdate'] == 8) $result['ajaxcode'] = 8;
                unset($tmp);
            }
            $this->model->shopCarClear();
        }

        return $result;
    }

    function ajaxShopcarUpdate($v) {
        $this->debugmsg('shopcarController::ajaxShopCarUpdate');

        parse_str($v, $this->request);
        $this->post = $this->request = array_stripslashes($this->request);

        $result = $this->shopCarList();

        $rr =& $this->ajax->add_node('result');
        $rr->set_data($result['ajaxcode']);

        $tt =& $this->ajax->add_node('total');
        $tt->set_data($result['totalprice']);

        $ta =& $this->ajax->add_node('totalamount');
        $ta->set_data($result['totalamount']);

        foreach ($result['list'] as $vv) {
            $i++;
            $r = "r{$i}";
            $p = "p{$i}";
            $t = "t{$i}";
            $a = "a{$i}";

            $$p =& $this->ajax->add_node('price');

            $$r =& $$p->add_node("id");
            $$r->set_data($vv['id']);

            $$t =& $$p->add_node("price");
            $$t->set_data($vv['amount']*$vv['price']);

            $$a =& $$p->add_node("amount");
            $$a->set_data($vv['amount']);
        }

        //处理数量为0的物品
        foreach ($this->request as $tmp_k=>$tmp_v) {
            if (!preg_match('/^amount/i', $tmp_k) || $tmp_v > 0) continue;
            $id = intval(str_replace('amount', '', $tmp_k));

            $i++;
            $r = "r{$i}";
            $p = "p{$i}";
            $t = "t{$i}";
            $a = "a{$i}";

            $$p =& $this->ajax->add_node('price');

            $$r =& $$p->add_node("id");
            $$r->set_data($id);

            $$t =& $$p->add_node("price");
            $$t->set_data(0);

            $$a =& $$p->add_node("amount");
            $$a->set_data(0);
        }
    }

    function checkout() {
        $this->debugmsg('shopcarController::checkout');

        $data['sessionid']  = $this->session['sid'];
        $data['uid']        = $this->session['id'];

        $data['postfee']    = intval($this->request['postfee']);
        //if ($data['postfee'] < 6) $data['postfee'] = 6;

        $data['paddr']      = intval($this->request['paddr']);
        $data['linkman']    = trim($this->request['linkman']);
        $data['tel']        = trim($this->request['tel']);
        $data['address']    = trim($this->request['address']);
        $data['zipcode']    = trim($this->request['zipcode']);
        $data['memo']       = trim($this->request['memo']);

        //来源uid，返点用
        $data['camefrom']   = $this->request['loopo_uid'] ? intval($this->request['loopo_uid']) : intval($this->cookie['camefrom']);

        //联系人
        $data['cman']       = trim($this->request['cman']);
        $data['cphone']     = trim($this->request['cphone']);
        $data['cemail']     = trim($this->request['cemail']);

        //是否需要包装
        $data['needpack']   = intval($this->request['needpack']);

        //检查库存是否足够
        $result['code']['recheck'] = $recheck = $this->model->shopCarUpdate(array('sessionid'=>$this->session['sid']));

        //购物车列表
        $result['shopcar']  = $this->shopCarList();

        //附加运费 (基本不用了 081123)
        foreach ($result['shopcar']['list'] as $v) $_postfee += $v['postfee'];

        //发货类型
        switch(intval($data['postfee']-$_postfee)) {
            case 0:
                $data['posttype'] = '免费快递';
                break;
            case 15:
            case 12:
            case 10:
                $data['posttype'] = '普通快递';
                break;
            case 20:
                $data['posttype'] = '次日达速递';
                break;
            case 25:
                $data['posttype'] = 'EMS';
                break;
            default:
                $data['posttype'] = '邮政包裹';
        }

        //折扣代码
        if ($this->request['voucher_code']) {
            //折扣代码不能和 VIP 共用，所以这里要重新计算总价
            //$result['shopcar']['totalprice'] = $result['shopcar']['list'][0]['amount'] * $result['shopcar']['list'][0]['price'];

            $_vc =& getController('voucher');
            $_vc_row = $_vc->getVoucher(array('price'=>$result['shopcar']['totalprice'], 'str'=>$this->request['voucher_code']));

            //如果可用
            if ($_vc_row['code']['getVoucher'] <=1 && $_vc_row['price'] > 0) {
                //就用
                $_off = $_vc->useVoucher(array('price'=>$result['shopcar']['totalprice']+$data['postfee'], 'str'=>$this->request['voucher_code']));
                $data['adjustfee'] += -$_off;
                $data['log'] = date('Y-m-d H:i:s')." [系统] 订单使用折扣代码 \"{$this->request['voucher_code']}\"，折扣金额 {$_off}\n";
            }
        }

        /*
        1.成功
        2.失败
        4.数据不完整
        8.购物车有变更
        */

        if ( (count($this->get)>1 || $this->post) && $result['shopcar']['list']) {
            if (isset($data['postfee']) && $data['linkman'] && $data['tel'] && $data['address'] && $data['zipcode']  || (!$data['linkman'] && !$data['tel'] && !$data['address'] && !$data['zipcode'] && $data['paddr'])) {

                //地址正确性检查
                if ( ($data['address'] && $data['tel'] && $data['zipcode']) && (strlen($data['address']) < 10 || strlen($data['tel']) < 7 || !preg_match('/^\d{5,6}$/', $data['zipcode'])) ) {
                    $result['code']['checkout'] = 4;
                } else {
                    if ($this->session['wish']) $data['address'] .= "(wishlist for {$this->session['wish']['username']})";

                    //新收货地址
                    if ($this->session['login'] && $data['linkman']) {
                        $uc =& getController('users');
                        $uc->userAddressAdd();
                    }

                    //相同的客户同一时间提交相同的定单，冲突处理
                    if ((int)$recheck == 8) {
                        $result['code']['checkout'] = 8;
                    } else {
                        do_action('shopcar_checkout_befor', array('data'=>&$data));
                        $result = $this->model->checkout($data);
                    }

                    //订单成功
                    if ($result['code']['checkout'] == 1) {
                        $this->session['caramount'] = 0;
                        $this->session['carprice'] = 0;

                        //折扣代码记录
                        if ($_vc) {
                            $_vc->VoucherIndent(array('vid'=>$_vc_row['id'], 'iid'=>$result['indentid'], 'off'=>$_off));
                            unset($_vc);
                        }

                        do_action('shopcar_indent_new', array('result'=>&$result));

                        //短信通知管理员
                        uses('sms');
                        $sms = new Sms;
                        $sms->newIndent($result['indentid']);
                    }
                }
            } else {
                $result['code']['checkout'] = 4;
            }

            $result['ajaxcode'] = $result['code']['checkout'];
        } elseif ($this->session['wish']) {
            //wishlist 自动填写地址
            $data['linkman']    = $this->session['wish']['info']['truename'];
            $data['tel']        = $this->session['wish']['info']['tel'];
            $data['address']    = $this->session['wish']['info']['address'];
            $data['zipcode']    = $this->session['wish']['info']['zipcode'];
            $data['memo']       = "默认情况下您的礼品是匿名赠送的\n如果您需要留言或者其它要求，请在此注明";
        }

        require_once ROOT.'controllers' .DS. 'users.php';
        $u =& new usersController;

        $data['uid'] = $this->session['id'];

        if ($data['uid']) $result['address']  = $u->model->userAddressList($data);
        $result['data']     = $data;

        return $result;
    }

    function ajaxCheckout($var) {
        parse_str($var, $this->request);

        $this->request = array_stripslashes($this->request);

        $result = $this->checkout();

        $r =& $this->ajax->add_node('result');
        $i =& $this->ajax->add_node('indentid');
        $r->set_data($result['ajaxcode']);
        $i->set_data($result['indentid']);
    }

    //礼品卡结帐
    //Gift Certificates
    function checkout_gc() {
        $this->debugmsg('shopcarController::checkout_gc');

        $data['sessionid']  = $this->session['sid'];
        $data['uid']        = $this->session['id'];

        $data['postfee']    = 0;
        $data['posttype']   = '礼品卡';

        //收货人
        /*
        $data['paddr']      = intval($this->request['paddr']);
        $data['tel']        = trim($this->request['tel']);
        $data['address']    = trim($this->request['address']);
        $data['zipcode']    = trim($this->request['zipcode']);
         */
        $data['linkman']    = trim($this->request['linkman']);
        $data['remail']     = trim($this->request['remail']);
        $data['address']    = trim($this->request['remail']);
        $data['memo']       = trim($this->request['memo']);

        //礼品卡金额
        $data['iid']        = intval($this->request['iid']);

        //联系人
        $data['cman']       = trim($this->request['cman']);
        $data['cphone']     = trim($this->request['cphone']);
        $data['cemail']     = trim($this->request['cemail']);

        //清空购物车，把礼品卡加入购物车
        if ($this->post) {
            $this->request['emptycar'] = 1;
            $this->shopCarUpdate();
            unset($this->request['emptycar']);

            $ic =& getController('items');
            $ic->addToCar($data['iid']);
        }

        //购物车列表
        if ($this->post) $result['shopcar']  = $this->shopCarList();

        //这里不允许用VIP折扣
        $result['shopcar']['totalprice'] = $result['shopcar']['list'][0]['amount'] * $result['shopcar']['list'][0]['price'];

        //Email发送
        $emailsend = $this->request['esend'] ? '是' : '否';
        if ($this->request['esend']) $emailsenddate = "发送日期:   {$this->request['y']}年{$this->request['m']}月{$this->request['d']}日";

        //Meta DATA
        $data['meta']['gift']['remail'] = $data['remail'];
        $data['meta']['gift']['message']= $data['memo'];
        $data['meta']['gift']['esend']  = $this->request['esend'];
        $data['meta']['gift']['esendtime'] = strtotime("{$this->request['y']}-{$this->request['m']}-{$this->request['d']}");

        //礼品卡信息
        if ($this->post) $data['memo'] = <<< EOF
礼品金额:   {$result['shopcar']['totalprice']} 元
想说的话:   {$data['memo']}
接收人:     {$data['linkman']}
接收 Email: {$data['remail']}
联系人:     {$data['cman']}
联系 Email: {$data['cemail']}
Email 发送: {$emailsend}
$emailsenddate
EOF;

        /*
        1.成功
        2.失败
        4.数据不完整
        8.购物车有变更
        */

        if ( (count($this->get)>1 || $this->post) && $result['shopcar']['list']) {
            if (isset($data['postfee']) && $data['remail'] && $data['linkman'] && $data['cman'] && $data['cphone']) {
                do_action('shopcar_checkout_gc_befor', array('data'=>&$data));
                $result = $this->model->checkout($data);

                //订单成功
                if ($result['code']['checkout'] == 1) {
                    $this->session['caramount'] = 0;
                    $this->session['carprice'] = 0;

                    do_action('shopcar_indent_new', array('result'=>&$result));

                    //短信通知管理员
                    uses('sms');
                    $sms = new Sms;
                    $sms->newIndent($result['indentid']);
                }
            } else {
                $result['code']['checkout'] = 4;
            }

            $result['ajaxcode'] = $result['code']['checkout'];
        }

        $result['data'] = $data;
        return $result;
    }
}
?>
